# -*- coding:utf-8 -*-

import json
import hmac
import hashlib
import base64
import urllib
from datetime import *


def get_json(obj):
    """
    返回封装好的json数据
    :param obj:
    :return:
    """
    s = json.dumps(obj, ensure_ascii=False)
    return s


def response_write(request_handler, obj):
    """
    往客户端返回数据
    :param obj:
    :param request_handler:
    :return:
    """
    s = json.dumps(obj, ensure_ascii=False)
    request_handler.set_header("Content-Type", "application/json; charset=UTF-8")
    request_handler.set_status(200, 'OK')
    request_handler.write(s)
    request_handler.finish()


def get_remote_ip(request_handler):
    """
    tornado获取客户端IP
    :param request_handler:被请求的request_handler
    :return:
    """
    # return request_handler.request.remote_ip # 用该方式获取的是服务器的ip,估计是nginx配置有问题
    x_forwarded_for = request_handler.request.headers.get('X-Forwarded-For')
    if x_forwarded_for:
        temp_ip_list = x_forwarded_for.split(',')
        real_ip = temp_ip_list[0]
    else:
        real_ip = request_handler.request.remote_ip
    # print 'real_ip:%s' %real_ip
    return real_ip


def generate_sign_param(key, data):
    """
    生成签名
    :param key:
    :param data:
    :return:
    """
    sign = hmac.new(key, data, hashlib.sha1).digest()
    sign_byte_array = bytearray(sign)
    data_byte_array = bytearray(data)
    param = base64.b64encode(sign_byte_array + data_byte_array)
    encoded_param = urllib.quote(param)
    return encoded_param


def character_to_lower(temp_character):
    """
    将传入的字符转为小写
    :param temp_character: str or unicode
    :return: str
    """
    temp_str = temp_character
    if isinstance(temp_character, unicode):
        temp_str = temp_character.encode('utf-8')
    return temp_str.lower()


def send_mail(send_to, subject, body, cc=None):
    import web
    web.config.smtp_server = 'mail.chem99.com'   # 邮件发送服务器
    web.config.smtp_port = 25    # 不设置将使用默认端口
    web.config.smtp_username = 'tech@chem99.com'   # 邮件服务器的登录名
    web.config.smtp_password = 'qazwsx.,/14789632'   # 邮件服务器的登录密码
    web.config.smtp_starttls = True
    send_from = 'tech@chem99.com'    # 发送的邮件
    web.sendmail(send_from, send_to, subject, body, cc=cc)


def format_float(input_float, decimal_place=None):
    """按规则格式化浮点数：

    如果没有小数，格式化成证书字符串；
    如果有小数，格式化成指定小数位数的字符串。

    prama input_float:
        type: float
    prama decimal_place:
        type: int
        desc: 格式化后保留的小数位数
        default: 原浮点数自带小数位数（最多六位）
    return:
        type: str
    """
    assert isinstance(input_float, float)
    if not decimal_place:
        decimal_place = _get_decimal_place(input_float)
    format_str = '{:.' + str(decimal_place) + 'f}'
    formated_float = format_str.format(input_float)
    if decimal_place > 0:
        formated_float_left, formated_float_right = formated_float.split('.')
        if int(formated_float_right) == 0:
            formated_float = formated_float_left
    return formated_float


def _get_decimal_place(input_float):
    """Get all decimal place of certain float input"""
    input_decimal_place = 0
    s_input = '{:f}'.format(input_float)
    _, s_input_right = s_input.split('.')
    for i in s_input_right:
        if i != '0':
            input_decimal_place += 1
    return input_decimal_place
